package org.elephas.webapp.frontend.component.common.form;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import org.apache.wicket.Component;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.IFormVisitorParticipant;
import org.apache.wicket.markup.html.form.RadioChoice;
import org.apache.wicket.markup.html.form.FormComponent.IVisitor;
import org.apache.wicket.model.ResourceModel;

/**
 * @author Gerolf Seitz
 */
public class ShinyFormVisitor implements IVisitor, Serializable {
	private static final long serialVersionUID = 1L;

	private Set<Component> visited = new HashSet<Component>();

	private String getLabelId(Component c) {
		return c.getId() + "Label";
	}

	public Object formComponent(IFormVisitorParticipant formComponent) {
		if (!isValidComponent(formComponent)) {
			return Component.IVisitor.CONTINUE_TRAVERSAL;
		}
		FormComponent component = (FormComponent) formComponent;
		if (!visited.contains(component)) {
			visited.add(component);

			FormComponent fc = (FormComponent) component;
			ShinyFormComponentLabel label = new ShinyFormComponentLabel(
					getLabelId(component), fc);
			fc.getParent().add(label);
			fc.setLabel(new ResourceModel(fc.getId()));
			component.add(new ErrorHighlightBehavior());
		}
		return Component.IVisitor.CONTINUE_TRAVERSAL;
	}

	private boolean isValidComponent(IFormVisitorParticipant fc) {
		return fc instanceof FormComponent && !(fc instanceof Button)
				&& !(fc instanceof CheckBox) && !(fc instanceof RadioChoice);
	}
}
